<?php
/*
	Aurus CMS - free OOP CMS
	Copyright (C) 2010  Nestor Yanchuk

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
class Image{
	static function loadImageByType($image){
		$type = @getimagesize($image);
		switch ($type['2']) {
			case IMAGETYPE_GIF:
				return imagecreatefromgif($image);
			case IMAGETYPE_JPEG:
				return imagecreatefromjpeg($image);
			case IMAGETYPE_PNG:
				return imagecreatefrompng($image);
			case IMAGETYPE_BMP:
				return imagecreatefromwbmp($image);
			default:
				return false;
		}
	}

	static function getResized($image,$w,$h,$margin = 10){
		$size = @getimagesize($image);
		$image = self::loadImageByType($image);
		$newImage = imagecreatetruecolor($w,$h);
		imagecopyresized($newImage,$image,0,0,0,0, $w, $h ,$size[0],$size[1]);
		
		for ($i= 0; $i <= 25; $i++) {
			imagefilter($newImage, IMG_FILTER_SMOOTH, 0);
		}
		
		$newW = $w - ($margin * 2);
		$newH = (int) $size[1] * ($newW / $size[0]);

		imagecopyresampled($newImage,$image,$margin - 1,($h - $newH) / 2, 0,0, $newW, $newH,$size[0],$size[1]);
		return $newImage;
	}

	static function outImage($i){
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Cache-Control: no-store, no-cache, must-revalidate");
		header("Cache-Control: post-check=0, pre-check=0", false);
		header("Pragma: no-cache");
		header("Content-Type: image/jpeg");

		if ( function_exists("imagejpeg")) {
			header("Content-type: image/jpeg");
			imagepng($i);
		} elseif (function_exists("imagegif")) {
			header("Content-type: image/gif");
			imagegif($i);
		} elseif (function_exists("imagepng")) {
			header("Content-type: image/png");
			imagejpeg($i,null,70);
		}
	}
}